//
//  TTextViewPlaceholder.m
//
//  Created by on 11. 12. 15..
//  Copyright 2011. All rights reserved.
//

#import "TTextViewPlaceholder.h"


@implementation TTextViewPlaceholder

@synthesize placeHolderLabel;
@synthesize placeHolder;
@synthesize placeHolderColor;


- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        [self setPlaceHolder:@""];
        [self setPlaceHolderColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    [self setPlaceHolder:@""];
    [self setPlaceHolderColor:[UIColor lightGrayColor]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)textChanged:(NSNotification *)notification
{
    if([[self placeHolder] length] == 0)
        return;
    
    if([[self text] length] == 0)
        [[self viewWithTag:999] setAlpha:1];
    else
        [[self viewWithTag:999] setAlpha:0];
}

- (void) clearText{
     [[self viewWithTag:999] setAlpha:1];
}

- (void)drawRect:(CGRect)rect 
{
    if( [[self placeHolder] length] > 0 )
    {
        if(self.placeHolderLabel == nil )
        {
            self.placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
            self.placeHolderLabel.lineBreakMode = UILineBreakModeWordWrap;
            self.placeHolderLabel.numberOfLines = 0;
            self.placeHolderLabel.font = self.font;
            self.placeHolderLabel.backgroundColor = [UIColor clearColor];
            self.placeHolderLabel.textColor = self.placeHolderColor;
            self.placeHolderLabel.alpha = 0;
            self.placeHolderLabel.tag = 999;
            [self addSubview:placeHolderLabel];
        }
        
        placeHolderLabel.text = self.placeHolder;
        [placeHolderLabel sizeToFit];
        [self sendSubviewToBack:placeHolderLabel];
    }
    
    if( [[self text] length] == 0 && [[self placeHolder] length] > 0 )
    {
        [[self viewWithTag:999] setAlpha:1];
    }
}

@end
